<?php

namespace jjl\yii2\db;

use Yii;
use yii\base\Model;

class Redis extends Model implements CacheInterface {

    private $_index;
    private $_handel;

    public function setIndex($value) {
        $this->_index = $value;
    }

    private function AssertHasRedis() {
        return Yii::$app->has('redis');
    }

    public function handle() {
        if (!$this->_handel)
            $this->_handel = Yii::$app->redis;
        return $this->_handel;
    }

    public function select(int $index) {
        if (!self::AssertHasRedis())
            return;
        call_user_func(array($this->handle(), 'SELECT'), $index);
    }

    /**
     * 
     * @param string $tag
     * @return $this
     */
    public function store(string $tag) {
        if (($index = $this->_index[$tag] ?? null))
            $this->select($index);
        return $this;
    }

    public function get(string $key) {
        if (!self::AssertHasRedis())
            return;
        $value = call_user_func(array($this->handle(), 'GET'), $key);
        if (($array = json_decode($value, true)))
            return $array;
        return $value;
    }

    public function set(string $key, $value, array $options = []) {
        if (!self::AssertHasRedis())
            return;
        if (!is_string($value))
            $value = json_encode($value);
        if (($expire = $options['expire'] ?? null)) {
            call_user_func(array($this->handle(), 'SET'), $key, $value, 'EX', $expire, 'NX');
        } else {
            call_user_func(array($this->handle(), 'SET'), $key, $value, 'NX');
        }
    }

    public function del(string $key) {
        if (!self::AssertHasRedis())
            return;
        call_user_func(array($this->handle(), 'DEL'), $key);
    }

}
